# -*- coding: utf-8 -*-
from tablestore import *
from GKModel.BaseModel import BaseModel


class Subject(BaseModel):
    TABLE_NAME = 'Subjects'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def query_subjects(self, type, next_start_primary_key=None, limit=10):
        inclusive_start_primary_key = [('key', INF_MIN)] \
            if next_start_primary_key is None \
            else next_start_primary_key
        exclusive_end_primary_key = [('key', INF_MAX)]
        columns_to_get = []
        cond = SingleColumnCondition('type', type, ComparatorType.EQUAL)

        def query():
            return self.ots_client.get_range(
                table_name=Subject.TABLE_NAME,
                direction=Direction.FORWARD,
                inclusive_start_primary_key=inclusive_start_primary_key,
                exclusive_end_primary_key=exclusive_end_primary_key,
                columns_to_get=columns_to_get,
                column_filter=cond,
                limit=limit,
                max_version=1
            )

        try:
            consumed, next_start_primary_key, row_list, next_token = query()

            result = []
            for row in row_list:
                item = dict(row.primary_key)
                for att in row.attribute_columns:
                    item[att[0]] = att[1]
                result.append(item)

            return result, next_start_primary_key
        except OTSServiceError as e:
            raise ValueError(1000022, e.get_error_message())
        except OTSClientError as e:
            raise ValueError(1000023, e.get_error_message())


def new(**kwargs) -> Subject:
    return Subject(**kwargs)
